package com.itheima.riggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.riggie.common.BaseContext;
import com.itheima.riggie.common.R;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 拦截器
* */
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null){
            BaseContext.setThreadLocal(empId);
            return true;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null){
            BaseContext.setThreadLocal(userId);
            return true;
        }


        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //没有登录,则不放行
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
